package com.ruoyi.system.flink;

import com.alibaba.nacos.shaded.com.google.common.util.concurrent.RateLimiter;
import com.alibaba.nacos.shaded.com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
public class RateLimiterTest {

    /**
     * RateLimiter 单机版 ：单进程 多线程的限流器
     * @param args
     */
    public static void main(String[] args) {
        int nodes = 1;//服务器的节点数
        int limit = 1;//限制数
        RateLimiter limiter = RateLimiter.create(limit / nodes);
        ThreadPoolExecutor executor = new ThreadPoolExecutor(nodes, nodes * 2, 6000l, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(1024), new ThreadFactoryBuilder().setNameFormat("consumer-limit-%d").build(),
            new ThreadPoolExecutor.CallerRunsPolicy());
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                double wait = limiter.acquire();
                log.info("######### nodes {}, qps {},等待 [{}] s ############",nodes,limit,wait);
                executor.execute(()->{
                    int time1 = 200;
                    log.info("添加远程耗时任务1");
                    log.info("执行远程耗时任务1开始，需要{}ms",time1);
                    try {
                        Thread.sleep(time1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    log.info("执行远程耗时任务1结束");
                    int time2 = 300;
                    log.info("添加远程耗时任务2");
                    log.info("执行远程耗时任务2开始，需要{}ms",time2);
                    try {
                        Thread.sleep(time2);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    log.info("执行远程耗时任务2结束");
                });
            }
            executor.shutdown();//提交完任务后关闭线程池
        },"limit").start();
    }
}
